<template>
  <div>
    <Header :title="'返回'" :subTitle="'营销活动'" :hasBackPath="true" @headerBack="headerBack"></Header>
    <a-spin :spinning="spinning" size="large">
      <a-card :bordered="false">
        <h2>{{ editTitle }}</h2>
        <div class="steps-head">
          <a-steps :current="current" size="small" v-if="triggerCondition == 4">
            <a-step v-for="item in stepsRed" :key="item.title" :title="item.title" />
          </a-steps>
          <a-steps :current="current" size="small" v-else>
            <a-step v-for="item in steps" :key="item.title" :title="item.title" />
          </a-steps>
        </div>
        <div class="steps-content">
          <!-- 基础设置 -->
          <section v-show="current == 0">
            <a-form-model ref="rulesFormP1" :model="form" :rules="rulesP1" :labelCol="labelCol" :wrapperCol="wrapperCol" style="min-height: 500px;">
              <a-form-model-item label="活动名称" prop="activityName">
                <a-input v-model="form.activityName" placeholder="请输入" :max-length="16" />
              </a-form-model-item>
              <a-form-model-item label="有效期类型" prop="validityType" required>
                <a-radio-group name="radioGroup" v-model="form.validityType">
                  <a-radio :value="1">固定时间</a-radio>
                  <a-radio :value="0">长期有效</a-radio>
                </a-radio-group>
              </a-form-model-item>
              <a-form-model-item label="活动时间" prop="timePicker" v-if="form.validityType == 1">
                <a-range-picker
                  style="width:100%;"
                  :show-time="{
                    hideDisabledOptions: true,
                    defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('11:59:59', 'HH:mm:ss')]
                  }"
                  :placeholder="['开始时间', '结束时间']"
                  v-model="form.timePicker"
                />
              </a-form-model-item>
              <a-form-model-item label="参活人群" prop="userType" required>
                <a-radio-group name="radioGroup" v-model="form.userType" @change="changeUserType">
                  <a-radio value="0">不限</a-radio>
                  <a-radio value="1">指定人群</a-radio>
                </a-radio-group>
              </a-form-model-item>
              <template v-if="form.userType == 1">
                <a-form-model-item prop="userTypeOther" :labelCol="{ lg: { span: 5 }, sm: { span: 7 } }" :wrapperCol="{ lg: { span: 10 }, sm: { span: 17, offset: 5 } }">
                  <a-select v-model="form.userTypeOther" placeholder="请选择" @change="changeLabel" show-search :filter-option="filterOption">
                    <a-select-option :value="item.id" v-for="(item, index) in memberList" :key="index">{{ item.memberName }}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </template>
              <a-form-model-item prop="activityType" required>
                <template v-slot:label>
                  <a-tooltip>
                    <template slot="title">
                      1、推广活动：该活动将生成带参码，通过对应的途径进入页面才能参与活动，同一时间允许存在多条活动
                      <br />
                      2、常规活动：无活动路径或带参码，正常进入原先对应页面即可参加活动，同一时间只允许存在一条活动
                    </template>
                    活动类型<a-icon type="question-circle" style="margin-left:4px" />
                  </a-tooltip>
                </template>
                <a-radio-group name="radioGroup" v-model="form.activityType">
                  <a-radio :value="1">推广活动</a-radio>
                  <a-radio :value="2">常规活动</a-radio>
                </a-radio-group>
              </a-form-model-item>
              <a-form-model-item label="是否对参与活动人群标记" prop="isFlag" required>
                <a-radio-group name="radioGroup" v-model="form.isFlag">
                  <a-radio :value="1">是</a-radio>
                  <a-radio :value="0">否</a-radio>
                </a-radio-group>
              </a-form-model-item>
              <template v-if="form.isFlag == 1">
                <a-form-model-item label="标记名称" prop="flagName">
                  <a-input v-model="form.flagName" placeholder="请输入" :max-length="16" />
                </a-form-model-item>
                <a-form-model-item label="标记颜色" prop="flagColour">
                  <a-input v-model="form.flagColour" placeholder="请选择颜色" type="color" style="width:100px" />
                  <span style="margin-left:12px;">颜色值：{{ form.flagColour }}</span>
                </a-form-model-item>
              </template>
            </a-form-model>
          </section>
          <!-- 页面设置 -->
          <template v-if="triggerCondition == 4">
            <a-form-model ref="rulesFormP2" :model="form" :rules="rulesP1" :labelCol="labelCol" :wrapperCol="wrapperCol" style="min-height: 500px;"></a-form-model>
            <section v-show="current == 1">
              红包
            </section>
          </template>
          <!-- 奖励设置 -->
          <section v-show="current == (triggerCondition == 4 ? 2 : 1)">
            <a-form-model ref="rulesFormP3" :model="form" :rules="rulesP3" :labelCol="labelCol" :wrapperCol="wrapperCol2" style="min-height: 500px;">
              <a-form-model-item label="奖励类型" required>
                <div style="border-bottom: 1px dashed #e5e5e5;">
                  <a-checkbox :checked="couponCheck" @change="e => onCheckChange(e, 'coupon')">优惠券</a-checkbox>
                  <div class="table-bg">
                    <a-table :columns="couponColumns" :data-source="coupon.couponList" :rowKey="(r, index) => index" :pagination="false">
                      <span slot="voucherNumber" slot-scope="t, record">
                        <a-input-number v-model="record.voucherNumber" :min="0" :max="100" />
                      </span>
                      <span slot="action" slot-scope="text, record, index">
                        <a-popconfirm title="确定删除吗?" ok-text="Yes" cancel-text="No" @confirm="handleDeleteProduct(index, 'coupon')">
                          <a><a-icon type="delete"/></a>
                        </a-popconfirm>
                        <!-- <a @click="handleDeleteProduct(index, 'coupon')"><a-icon type="delete"/></a> -->
                        <a-button style="margin-left:12px;padding:0" type="link" :disabled="index == 0" @click="handleUp(index, 'coupon')"><a-icon type="arrow-up"/></a-button>
                        <a-button style="margin-left:12px;padding:0" type="link" :disabled="index == coupon.couponList.length - 1" @click="handleDown(index, 'coupon')"
                          ><a-icon type="arrow-down"
                        /></a-button>
                      </span>
                    </a-table>
                    <a-button icon="plus" type="link" style="float:right;" @click="openCoupons">新增优惠券</a-button>
                    <p style="margin-top:12px;margin-bottom:18px;clear:both;">奖励上限为：<a-input-number v-model="coupon.couponTotalNumber" :min="0" :max="99999999" /> 份</p>
                  </div>
                </div>
                <div style="margin-top:18px">
                  <a-checkbox :checked="goodsCheck" @change="e => onCheckChange(e, 'goods')">实物</a-checkbox>
                  <div class="table-bg">
                    <a-table :columns="goodsColumns" :data-source="goods.goodsList" :rowKey="(r, index) => index" :pagination="false" :scroll="{ x: 900 }">
                      <span slot="image" slot-scope="text">
                        <img :src="text" alt="" class="thumb" />
                      </span>
                      <span slot="action" slot-scope="text, record, index">
                        <a @click="handleEditProduct(record, index, 'goods')"><a-icon type="edit"/></a>
                        <a-popconfirm title="确定删除吗?" ok-text="Yes" cancel-text="No" @confirm="handleDeleteProduct(index, 'goods')" style="margin-left:12px;">
                          <a><a-icon type="delete"/></a>
                        </a-popconfirm>
                        <!-- <a @click="handleDeleteProduct(index, 'goods')"><a-icon type="delete"/></a> -->
                        <a-button style="margin-left:12px;padding:0" type="link" :disabled="index == 0" @click="handleUp(index, 'goods')"><a-icon type="arrow-up"/></a-button>
                        <a-button style="margin-left:12px;padding:0" type="link" :disabled="index == goods.goodsList.length - 1" @click="handleDown(index, 'goods')"
                          ><a-icon type="arrow-down"
                        /></a-button>
                      </span>
                    </a-table>
                    <a-button icon="plus" type="link" style="float:right;" @click="addGoods">新增物品</a-button>
                    <p style="margin-top:12px;clear:both;">奖励上限为：<a-input-number v-model="goods.goodsTotalNumber" :min="0" :max="99999999" /> 份</p>
                  </div>
                </div>
                <div class="tip" v-show="tipReward">{{ tipText }}</div>
              </a-form-model-item>
              <a-form-model-item label="奖励限制" required>
                <p>
                  <!-- <a-checkbox :checked="everydayCheck" @change="e => onCheckChange(e, 'everyday')">每人每日可享奖励份数</a-checkbox> -->
                  每人每日可享奖励份数：<a-input-number v-model="form.everydayRewardNumber" :min="0" />
                </p>
                <p>
                  <!-- <a-checkbox :checked="rewardNumberCheck" @change="e => onCheckChange(e, 'reward')">每人累计可享奖励份数</a-checkbox> -->
                  每人累计可享奖励份数：<a-input-number v-model="form.rewardNumber" :min="0" />
                </p>
                <div class="tip" v-show="showReward">请输入奖励份数</div>
              </a-form-model-item>
              <a-form-model-item label="奖励方式" v-if="false"></a-form-model-item>
            </a-form-model>
          </section>
          <!-- 分享设置 -->
          <section v-show="current == (triggerCondition == 4 ? 3 : 2)">
            <a-form-model ref="rulesFormP4" :model="form" :rules="rulesP4" :labelCol="labelCol" :wrapperCol="wrapperCol" style="min-height: 500px;">
              <a-form-model-item label="小程序端系统转发好友功能" required>
                <a-switch v-model="transmitFriend" />
              </a-form-model-item>
              <a-form-model-item label="小程序端系统分享朋友圈功能" required>
                <a-switch v-model="shareFriend" />
              </a-form-model-item>
              <a-form-model-item label="微信素材" required>
                <div class="xcx" v-show="form.materialId">
                  <a-card hoverable v-if="bwxMaterial" class="xcx-card">
                    <img slot="cover" :src="bwxMaterial.imgUrl" alt="" class="img-cover" />
                    <a-card-meta>
                      <template slot="title">
                        <ellipsis :length="20" tooltip>{{ bwxMaterial.createTime }}</ellipsis>
                      </template>
                      <template slot="description">
                        {{ bwxMaterial.title }}
                      </template>
                    </a-card-meta>
                  </a-card>
                </div>
                <a-button @click="openMaterial" style="margin-top:16px">选择微信素材</a-button>
                <span v-show="showwxTip && !form.materialId" class="tip">请选择微信素材</span>
              </a-form-model-item>
            </a-form-model>
          </section>

          <div class="steps-action">
            <a-button v-if="current > 0" @click="prev" style="margin-right: 18px">
              上一步
            </a-button>
            <a-button v-if="current < steps.length - 1" type="primary" @click="next">
              下一步
            </a-button>
            <a-button v-if="current == steps.length - 1" type="primary" @click="handleSubmit" :loading="saveLoading" :disabled="form.status == 2 || form.status == 3">
              保存
            </a-button>
            <!-- <a-button v-if="current == steps.length - 1" type="primary" @click="submitAndKeep" style="margin-left:18px">
              保存，继续添加搭配
            </a-button> -->
          </div>
        </div>
      </a-card>
    </a-spin>
    <CouponModal ref="couponModal" @handleAddCoupons="handleAddCoupons"></CouponModal>
    <AddGoodsModal ref="addGoodsModal" @handleAddGoods="handleAddGoods"></AddGoodsModal>
    <MaterialModal ref="materialModal" @getChoose="getChoose"></MaterialModal>
  </div>
</template>
<script>
import moment from 'moment'
import 'moment/locale/zh-cn'
import { initDictFromBox } from '@/views/box/util/global'
import Header from '@/views/box/components/layouts/Header'
import JImageUpload from '@/components/qiniuUpload/JImageUpload.vue'
import { CouponModal, Ellipsis } from '@/views/box/components'
import AddGoodsModal from './components/addGoodsModal'
import MaterialModal from '@/views/box/components/wxMaterialModal'
import { marketingActivityAdd, marketingActivityEdit, marketingActivityDetail } from '@/api/box/marketing'
import { marketingMemberList } from '@/api/box/member'
import { couponList } from '@/api/box/setting'
let couponColumns = [
  { title: '优惠券ID', dataIndex: 'voucherId', align: 'center' },
  { title: '优惠券名称', dataIndex: 'entityName', align: 'center' },
  { title: '张数', dataIndex: 'voucherNumber', align: 'center', scopedSlots: { customRender: 'voucherNumber' } },
  { title: '顺序', align: 'center', customRender: (t, r, index) => index + 1 },
  { title: '操作', fixed: 'right', align: 'center', scopedSlots: { customRender: 'action' } }
]
let goodsColumns = [
  { title: '类型', dataIndex: 'entityType', align: 'center', customRender: text => (text == 1 ? '内部商品' : '外部商品'), width: 100 },
  { title: '款号', dataIndex: 'voucherId', align: 'center' },
  { title: '名称', dataIndex: 'entityName', align: 'center' },
  { title: '图片', dataIndex: 'image', align: 'center', scopedSlots: { customRender: 'image' } },
  { title: '份数', dataIndex: 'voucherNumber', align: 'center', width: 80 },
  { title: '顺序', align: 'center', width: 80, customRender: (t, r, index) => index + 1 },
  { title: '操作', fixed: 'right', align: 'center', width: 130, scopedSlots: { customRender: 'action' } }
]
export default {
  components: { Header, JImageUpload, CouponModal, AddGoodsModal, MaterialModal, Ellipsis },
  data() {
    return {
      couponColumns,
      goodsColumns,
      actId: '',
      triggerCondition: '',
      editTitle: '',
      sceneList: [],
      current: 0,
      steps: [
        { title: '基础设置', content: 'First-content' },
        { title: '奖励设置', content: 'Second-content' },
        { title: '分享设置', content: 'Second-content' }
      ],
      stepsRed: [
        { title: '活动设置', content: 'First-content' },
        { title: '页面设置', content: 'Second-content' },
        { title: '奖励设置', content: 'First-content' },
        { title: '分享设置', content: 'Second-content' }
      ],
      labelCol: { lg: { span: 5 }, sm: { span: 7 } },
      wrapperCol: { lg: { span: 10 }, sm: { span: 17 } },
      wrapperCol2: { lg: { span: 15 }, sm: { span: 17 } },
      originData: {},
      form: {
        validityType: 1,
        userType: '0',
        userTypeOther: null,
        activityType: 1,
        isFlag: 1,
        flagColour: '#00000'
        // timePicker: [null, null]
      },
      rulesP1: {
        activityName: [{ required: true, message: '请输入活动名称，最多16个字', trigger: 'blur' }],
        validityType: [{ required: true }],
        timePicker: [{ required: true, message: '请输入活动时间' }],
        userTypeOther: [{ required: true, message: '请选择指定人群', trigger: ['change', 'blur'] }]
      },
      rulesP2: {},
      rulesP3: {},
      rulesP4: {},
      memberList: [],
      couponCheck: false,
      goodsCheck: false,
      coupon: {
        couponList: [],
        couponTotalNumber: '',
        openNumber: 0
      },
      goods: {
        goodsList: [],
        goodsTotalNumber: '',
        openNumber: 0
      },
      currentEditIndex: null,
      everydayCheck: true,
      rewardNumberCheck: true,
      tipText: '',
      tipReward: false,
      showReward: false,

      transmitFriend: true,
      shareFriend: true,
      bwxMaterial: {},
      showwxTip: false,

      spinning: false,
      saveLoading: false
    }
  },
  mounted() {
    this.initPage()
    this.labelMemberList()
  },
  deactivated() {
    this.$destroy()
  },
  methods: {
    moment,
    headerBack() {
      this.$router.back()
    },
    next() {
      this.validate(this.current)
    },
    /*
     * 校验每一步form
     */
    validate(current) {
      if (current == 0) {
        this.$refs.rulesFormP1.validate(valid => {
          if (valid) {
            this.current++
          }
        })
      } else if (current == 1) {
        if (this.triggerCondition == 4) {
          this.$refs.rulesFormP2.validate(valid => {
            if (valid) {
              this.current++
            }
          })
        } else {
          this.validateFormP3()
        }
      } else if (current == 2) {
        if (this.triggerCondition == 4) {
          this.validateFormP3()
        } else {
          // 保存
        }
      } else if (current == 3) {
        // triggerCondition:4 保存
      }
    },
    validateFormP3() {
      this.$refs.rulesFormP3.validate(valid => {
        if (!this.couponCheck && !this.goodsCheck) {
          this.tipText = '至少选择一种奖励'
          this.tipReward = true
          return
        } else {
          if (this.couponCheck) {
            if (this.coupon.couponList.length == 0) {
              this.tipText = '请添加优惠券'
              this.tipReward = true
              return
            } else {
              let result = this.coupon.couponList.filter(e => e.voucherNumber)
              if (result.length != this.coupon.couponList.length) {
                this.tipText = '请补全优惠券张数'
                this.tipReward = true
                return
              } else if (!this.coupon.couponTotalNumber) {
                this.tipText = '请输入优惠券总数'
                this.tipReward = true
                return
              }
            }
          }
          if (this.goodsCheck) {
            if (this.goods.goodsList.length == 0) {
              this.tipText = '请添加实物奖励'
              this.tipReward = true
              return
            } else {
              if (!this.goods.goodsTotalNumber) {
                this.tipText = '请输入实物总数'
                this.tipReward = true
                return
              }
            }
          }
        }
        this.tipText = ''
        this.tipReward = false

        if (!this.form.everydayRewardNumber) {
          this.showReward = true
          return
        }
        if (!this.form.rewardNumber) {
          this.showReward = true
          return
        }
        if (valid) {
          this.tipText = ''
          this.tipReward = false
          this.showReward = false
          this.current++
        }
      })
    },
    prev() {
      this.current--
    },
    getScenceList() {
      return initDictFromBox('marketing_scene').then(res => {
        this.sceneList = res
      })
    },
    async initPage() {
      this.spinning = true
      this.actId = this.$route.params.id
      this.triggerCondition = this.$route.params.type

      await this.getScenceList()
      let tcTitle = this.sceneList.filter(e => e.code == this.triggerCondition)
      if (this.actId == 'add') {
        this.form.triggerCondition = this.triggerCondition
        if (tcTitle.length > 0) {
          this.editTitle = `新建 ${tcTitle[0].name}`
        } else {
          this.editTitle = '新建活动'
        }
      } else {
        await this.fetchDetail()
        if (this.triggerCondition == 'copy') {
          tcTitle = this.sceneList.filter(e => e.code == this.form.triggerCondition)
          if (tcTitle.length > 0) {
            this.editTitle = `新建 ${tcTitle[0].name}`
          } else {
            this.editTitle = '新建活动'
          }
          this.form.status = 1
        } else {
          if (tcTitle.length > 0) {
            this.editTitle = `编辑 ${tcTitle[0].name}`
          } else {
            this.editTitle = '编辑活动'
          }
        }
      }
      this.spinning = false
    },
    fetchDetail() {
      let params = {
        requestData: {
          id: this.actId
        }
      }
      return marketingActivityDetail(params).then(res => {
        if (res.code == 0) {
          this.originData = res.data
          this.form = JSON.parse(JSON.stringify(res.data))
          if (this.form.validityType == 1) {
            this.$set(this.form, 'timePicker', [moment(this.form.startTime), moment(this.form.endTime)])
          }

          if (res.data.userType != 0) {
            this.form.userTypeOther = res.data.userType ? res.data.userType : null
            this.form.userType = '1'
          } else {
            this.form.userType = '0'
          }
          console.log(this.form)
          this.transmitFriend = this.form.transmitFriend == 1
          this.shareFriend = this.form.shareFriend == 1
          this.bwxMaterial = this.form.bwxMaterial ? this.form.bwxMaterial : null

          this.everydayCheck = this.form.everydayRewardNumber > 0
          this.rewardNumberCheck = this.form.rewardNumber > 0

          let couponList = this.form.bactivityRewardList.filter(e => e.rewardType == 1)
          let goodsList = this.form.bactivityRewardList.filter(e => e.rewardType == 2)
          if (couponList.length > 0) {
            this.coupon = {
              couponList: couponList.sort(this.compare('seq')),
              couponTotalNumber: couponList.sort(this.compare('seq'))[0].totalNumber,
              openNumber: this.triggerCondition == 'copy' ? 0 : couponList.sort(this.compare('seq'))[0].openNumber
            }
            /* let ids = this.coupon.couponList.map(e => e.voucherId)
            this.fetchCurrentCoupons(ids) */
            this.couponCheck = true
          }
          if (goodsList.length > 0) {
            this.goods = {
              goodsList: goodsList.sort(this.compare('seq')),
              goodsTotalNumber: goodsList.sort(this.compare('seq'))[0].totalNumber,
              openNumber: this.triggerCondition == 'copy' ? 0 : goodsList.sort(this.compare('seq'))[0].openNumber
            }
            this.goodsCheck = true
          }
        }
      })
    },
    // 排序
    compare(property) {
      return function(a, b) {
        var value1 = a[property]
        var value2 = b[property]
        return value1 - value2
      }
    },
    onCheckChange(e, type) {
      switch (type) {
        case 'coupon':
          this.couponCheck = !this.couponCheck
          break
        case 'goods':
          this.goodsCheck = !this.goodsCheck
          break
        case 'everyday':
          this.everydayCheck = !this.everydayCheck
          break
        case 'reward':
          this.rewardNumberCheck = !this.rewardNumberCheck
          break
      }
    },
    onNumberChange(value, type) {
      switch (type) {
        case 'everyday':
          this.everydayCheck = value > 0
          break
        case 'reward':
          this.rewardNumberCheck = value > 0
          break
      }
    },
    /**
     * 参活人群：指定人群筛选
     */
    changeUserType(e) {
      let value = e.target.value
      if (value == 1 && this.originData.userType != 0) {
        this.form.userTypeOther = this.originData.userType
      }
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    changeLabel(v) {
      console.log(v)
      this.form.userTypeOther = v
      this.$forceUpdate()
    },
    /*
     * 会员标签列表，选择启用的标签
     */
    labelMemberList() {
      let params = {
        page: {
          pageNo: 1,
          pageSize: 100
        },
        requestData: { status: 1 }
      }
      marketingMemberList(params).then(res => {
        if (res.code == 0) {
          this.memberList = res.data
        }
      })
    },
    // 回显券
    fetchCurrentCoupons(list) {
      let params = {
        requestData: {
          ruleIds: list
        },
        page: {
          pageNo: 1,
          pageSize: 100
        }
      }
      couponList(params).then(res => {
        if (res.code == 0) {
          for (let item of this.coupon.couponList) {
            let result = res.data.filter(e => e.id == item.voucherId)
            if (result.length > 0) {
              item.voucherName = result[0].name
            } else {
              item.voucherName = ''
            }
          }
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    // 新增奖励
    openCoupons() {
      this.$refs.couponModal.show()
    },
    addGoods() {
      this.currentEditIndex = null
      this.$refs.addGoodsModal.show()
    },
    handleAddCoupons(list) {
      let newList = list.map(e => {
        return {
          voucherId: e.id,
          voucherNumber: 0,
          entityName: e.name,
          rewardType: 1
        }
      })
      let coupons = [...this.coupon.couponList, ...newList]
      let newArr = coupons.filter((currentValue, currentIndex, sourceArr) => {
        return sourceArr.findIndex(x => x.voucherId === currentValue.voucherId) === currentIndex
      })
      this.coupon.couponList = newArr
      this.couponCheck = true
    },
    handleAddGoods(list) {
      if (this.currentEditIndex != null) {
        this.goods.goodsList[this.currentEditIndex] = list[0]
      } else {
        this.goods.goodsList = [...this.goods.goodsList, ...list]
      }
      this.goodsCheck = true
      this.currentEditIndex = null
      this.$forceUpdate()
    },
    // 奖励操作
    handleDeleteProduct(index, type) {
      switch (type) {
        case 'coupon':
          this.coupon.couponList.splice(index, 1)
          if (this.coupon.couponList.length == 0) this.couponCheck = false
          break
        case 'goods':
          this.goods.goodsList.splice(index, 1)
          if (this.goods.goodsList.length == 0) this.goodsCheck = false
      }
    },
    handleEditProduct(record, index, type) {
      if (type == 'goods') {
        this.currentEditIndex = index
        let editRecord = JSON.parse(JSON.stringify(record))
        this.$refs.addGoodsModal.show(editRecord)
      }
    },
    handleUp(i, type) {
      let list = []
      switch (type) {
        case 'coupon':
          list = JSON.parse(JSON.stringify(this.coupon.couponList))
          ;[list[i - 1], list[i]] = [list[i], list[i - 1]]
          console.log(list)
          this.coupon.couponList = list
          break
        case 'goods':
          list = JSON.parse(JSON.stringify(this.goods.goodsList))
          ;[list[i - 1], list[i]] = [list[i], list[i - 1]]
          console.log(list)
          this.goods.goodsList = list
          break
      }
    },
    handleDown(i, type) {
      let list = []
      switch (type) {
        case 'coupon':
          list = JSON.parse(JSON.stringify(this.coupon.couponList))
          ;[list[i + 1], list[i]] = [list[i], list[i + 1]]
          console.log(list)
          this.coupon.couponList = list
          break
        case 'goods':
          list = JSON.parse(JSON.stringify(this.goods.goodsList))
          ;[list[i + 1], list[i]] = [list[i], list[i + 1]]
          console.log(list)
          this.goods.goodsList = list
          break
      }
    },
    // 微信素材
    openMaterial() {
      this.$refs.materialModal.show()
    },
    getChoose(item) {
      console.log(item)
      this.bwxMaterial = item
      this.form.materialId = item.id
    },
    // 保存
    async handleSubmit() {
      this.$refs.rulesFormP4.validate(valid => {
        if (!this.form.materialId) {
          this.showwxTip = true
          return
        }
        if (valid) {
          this.saveLoading = true
          this.showwxTip = false
          let rewardList = []
          if (this.couponCheck) {
            let cl = this.coupon.couponList.map((item, index) => {
              item.totalNumber = this.coupon.couponTotalNumber
              item.openNumber = this.coupon.openNumber
              item.seq = index
              return item
            })
            rewardList = [...rewardList, ...cl]
          }
          if (this.goodsCheck) {
            let gl = this.goods.goodsList.map((item, index) => {
              item.totalNumber = this.goods.goodsTotalNumber
              item.openNumber = this.goods.openNumber
              item.seq = index
              return item
            })
            rewardList = [...rewardList, ...gl]
          }
          console.log(rewardList)

          let formValue = {}
          Object.keys(this.form).forEach(i => {
            if (this.form[i] !== '' && this.form[i] !== undefined && this.form[i] !== null) {
              if (i == 'timePicker' && this.form.validityType == 1) {
                formValue.startTime = this.form[i][0].format('YYYY-MM-DD HH:mm:ss')
                formValue.endTime = this.form[i][1].format('YYYY-MM-DD HH:mm:ss')
              } else if (i == 'userType') {
                if (this.form[i] == '0') {
                  formValue[i] = this.form[i]
                } else {
                  formValue[i] = this.form.userTypeOther
                }
              } else if (i == 'isFlag') {
                formValue[i] = this.form[i]
                if (this.form[i] == 1) {
                  formValue.flagName = this.form.flagName
                  formValue.flagColour = this.form.flagColour
                }
              } else {
                formValue[i] = this.form[i]
              }
            }
          })
          formValue.bactivityRewardList = rewardList
          formValue.transmitFriend = this.transmitFriend ? 1 : 0
          formValue.shareFriend = this.shareFriend ? 1 : 0

          delete formValue.userTypeOther
          console.log(formValue)
          if (this.triggerCondition == 'copy' || this.actId == 'add') {
            delete formValue.id
            this.submitAdd(formValue)
          } else {
            this.submitEdit(formValue)
          }
        }
      })
    },
    submitAdd(formValue) {
      let params = {
        requestData: formValue
      }
      marketingActivityAdd(params).then(res => {
        if (res.code == 0) {
          this.$message.success('新增成功！')
          this.headerBack()
        } else {
          this.$message.warning(res.msg)
          this.saveLoading = false
        }
      })
    },
    submitEdit(formValue) {
      let params = {
        requestData: formValue
      }
      marketingActivityEdit(params).then(res => {
        if (res.code == 0) {
          this.$message.success('编辑成功！')
          this.headerBack()
        } else {
          this.$message.warning(res.msg)
          this.saveLoading = false
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
@import '../../assets/style/xcx.less';
.steps-head {
  width: 60%;
  margin: 0 auto 24px;
  overflow: hidden;
}
.steps-content {
  min-height: 540px;
}
.steps-action {
  margin-top: 36px;
  display: flex;
  justify-content: center;
}
.thumb {
  width: 50px;
  height: 50px;
  object-fit: scale-down;
}
.tip {
  color: #f5222c;
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: -1px;
}
</style>

